<template>
	<view >
		<!-- 导航栏组件 -->
		<freenavbar showBack zwStatus :title="title" fixedStatus>
			<text slot="left" @click="back" class="iconfont icon-zuojiantou text-dark px-2" style="font-size: 40rpx;"></text>
			<text slot="right" @click="toSet" class="iconfont icon-gengduo text-dark px-2" style="font-size: 40rpx;"></text>
		</freenavbar>
		
		<!-- 聊天内容区域 -->
		<scroll-view :scroll-top="scrollTop" scroll-y class="scroll bg-light wrapper position-fixed left-0 right-0 px-3" style="bottom: 105rpx;" :style="chartBodyBottom" :show-scrollbar="false" scroll-with-animation>
			<!-- 聊天信息列表组件 -->
			<block class="cu-item" v-for="(item,index) in list" :key="index">
				<freeChatItem @preview="preview" @long="long" :item="item" :index="index" ref="chatItem" :pretime="index > 0?list[index-1].create_time:0"/>
			</block>
		</scroll-view>
		
		<!-- 透明的遮罩层 -->
		<div v-if="mode === 'action'||mode === 'emoticon'" style="z-index: 2;" class="position-fixed  top-0 left-0 right-0 bottom-0" @click="clickPage"  :style="'bottom:'+maskBotto+'px'"></div>
		
		<!-- 底部输入框 -->
		<view class="position-fixed flex align-center  left-0 right-0 border-top " style="background-color: #f7f7f6; height: 105rpx;" :style="'bottom:'+keyboardHeight+'px'">
			<!-- 左侧切换按钮 -->
			<view @click="change">
				<text v-if="mode == 'audio'" class="iconfont icon-jianpan font text-dark px-2" style="font-size: 40rpx;"></text>
				<text v-else class="iconfont icon-yuyin font text-dark px-2" style="font-size: 40rpx;"></text>
			</view>
			
			<!-- 中间内容输入 -->
			<block>
				<view @tap="startRecord" v-if="mode == 'audio'" :class="isRecording?'bg-hover-light':'bg-white'" class="text-dark font" style="text-align: center;border-radius: 10rpx;;padding: 20rpx 10rpx;width: 80%;" @touchstart="voiceTouchStart" @touchend="voiceTouchEnd" @touchcancel="voiceTouchCancel" @touchmove="voiceTouchMove">{{isRecording?'松开 结束':'按住 说话'}}</view>
				<textarea v-else :adjust-position="false" fixed class="bg-white p-1 rounded font-md" style="height: 60rpx;padding: 20rpx 0px 0px 0px;" v-model.trim="text" @focus="mode = 'text'"/>
			</block>
			
			<!-- 表情 --> 
			<text @click="openActionOrEmoticon('emoticon')" class="iconfont icon-biaoqing text-dark px-2" style="font-size: 40rpx;"></text>
			<!-- 扩展菜单 -->
			<text @click="openActionOrEmoticon('action')" v-if="text.length == 0" class="iconfont icon-jiahao1 text-dark px-2" style="font-size: 40rpx;"></text>
			<!-- 发送按钮 -->
			<view style="width: 80rpx;" v-if="text.length != 0" class="main-bg-color rounded py-1 px-2 mr-2" @click="send('text')">
				<text class="font text-white">发送</text>
			</view>
		</view>
		  
		<!-- 扩展菜单 -->
		<freePopup bottom ref="action" @hiden="keyboardHeight = 0" :mask="false">
			<view class="border-top border-light-secondary bg-light" style="height: 580rpx;">
				<swiper :indicator-dots="true" style="height: 550rpx;">
					<swiper-item style="margin: 0 auto;" class="row justify-center" v-for="(item,index) in emoticonOrActionList" :key="index">
						<view @click="actionEvent(items)" class="col-3 flex align-center flex-column justify-center" style="height: 255rpx;" v-for="(items,indexs) in item" :key="indexs" >
							<image :src="items.icon" mode="widthFix" style="width: 100rpx;height: 100rpx;"></image>
							<text class="font text-muted mt-2">{{items.name}}</text>
						</view>
					</swiper-item> 
				</swiper>
			</view>
		</freePopup>
		<!-- 弹出层 -->
		<freePopup ref="extend" :bodyWidth="240" :bodyHeight="getMenusHeight" :tabbarHeight="105">
			<view class="flex flex-column shadow-lg" style="width: 240rpx;" :style="getMenusStyle">
				<view class="flex-1 flex align-center" hover-class="bg-light" v-for="(item,index) in menusList" :key="index" @click="clickEvent(item.event,item.name)">
					<text class="font-md pl-3">{{item.name}}</text>
				</view>
			</view>
		</freePopup>
		
		<!-- 录音提示 -->
		<view v-if="isRecording" class="position-fixed left-0 top-0 right-0 flex align-center justify-center" style="bottom: 105rpx;">
			<view class="rounded flex flex-column align-center justify-center" style="width: 360rpx;height: 360rpx;background-color: rgba(0,0,0,0.5);">
				<image src="/static/audio/recording.gif" style="width: 150rpx;height: 150rpx;"></image>
				<text class="font text-white mt-3">{{unRecord?'松开手指，取消发送':'手指上滑，取消发送'}}</text>
			</view>
		</view>
	</view>
</template>

<script>
	// const domModule = weex.requireModule('dom')
	const RECORD = uni.getRecorderManager();
	import freenavbar from'@/components/free-ui/free-nav-bar';//顶部导航组件
	import freeChatItem from'@/components/free-ui/free-chat-item'//聊天列表组件
	import freePopup from'@/components/free-ui/free-popup';//弹出层组件
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	
	innerAudioContext.autoplay = true;
	export default {
		components:{freenavbar,freeChatItem,freePopup},
		data() {
			return {
				scrollTop: 1000, //滑动距离
				mitemHeight: 0, //所有消息的高
				windowHeight: 0, //显示的高度
				// 模式 text输入文字  emoticon表情 action操作菜单 qudio音频
				mode:'audio',
				actionList:[  //扩展菜单列表
					[
						{
							name:'相册',
							icon:'/static/images/extends/pic.png',
							event:'uploadImage'
						},
						{
							name:'拍摄',
							icon:'/static/images/extends/video.png',
							event:'uploadVideo'
						},
						{
							name:'视频通话',
							icon:'/static/images/extends/phone.png',
							event:''
						},
						{
							name:'位置',
							icon:'/static/images/extends/path.png',
							event:''
						},
						{
							name:'红包',
							icon:'/static/images/extends/hongbao.png',
							event:''
						},
						{
							name:'转账',
							icon:'/static/images/extends/man.png',
							event:''
						},
						{
							name:'语音输入',
							icon:'/static/images/extends/audio.png',
							event:''
						},
						{
							name:'我的收藏',
							icon:'/static/images/extends/shoucan.png',
							event:''
						},
					],
					[
						{
							name:'相册',
							icon:'/static/images/extends/pic.png',
							event:''
						},
						{
							name:'拍摄',
							icon:'/static/images/extends/video.png',
							event:''
						},
						{
							name:'视频通话',
							icon:'/static/images/extends/phone.png',
							event:''
						},
						{
							name:'位置',
							icon:'/static/images/extends/path.png',
							event:''
						},
						{
							name:'红包',
							icon:'/static/images/extends/hongbao.png',
							event:''
						},
						{
							name:'转账',
							icon:'/static/images/extends/man.png',
							event:''
						},
						{
							name:'语音输入',
							icon:'/static/images/extends/audio.png',
							event:''
						},
						{
							name:'我的收藏',
							icon:'/static/images/extends/shoucan.png',
							event:''
						},
					],
				],
				emoticonList:[
					[
						{
							name:'沮丧',
							icon:'/static/images/emoticon/5497/0.gif',
							event:''
						},
					]
				],
				keyboardHeight:0,//键盘高度
				title:'与张三的聊天',//组件导航栏的标题内容
				navBarHeight:45,
				propIndex:-1,//当前操作的气泡索引
				text:'',//输入文字
				
				// 音频录制状态
				isRecording:false, //音频录制的状态
				RecordingStartY:0,//手指按住录音是的位置信息
				unRecord:false,//取消录音
				RecordTime:0,//录音时长
				RECORDTIMER:null,//定义一个定时器
				
				list:[
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'资料发我下',
						create_time:1597575763,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'1688物流编号：557062785123420',
						create_time:1629108163,
						isremove:true
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'订单号：2108082155PWM8R',
						create_time:1626433363,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'image',//images video  audio file share
						data:'/static/images/demo/cate_banner.png',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'就这些了',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'audio',//images video  audio file share
						data:'/static/audio/1.mp3',
						options:{
							time:10
						},
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'audio',//images video  audio file share
						data:'/static/audio/2.mp3',
						options:{
							time:50
						},
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:2,
						nickname:'昵称',
						type:'audio',//images video  audio file share
						data:'/static/audio/3.mp3',
						options:{
							time:30
						},
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'好的',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'下班了',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'晚上打王者吗',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'可以呀😁😁😁',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'😎😎😎🤩😛🎁🧧',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'你是什么段位?',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'video',//images video  audio file share
						data:'/static/video/demo3.mp4',
						options:{
							poster:'/static/video/demo3.png'
						},
						create_time:1629367911,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo3.jpg',
						user_id:2,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'最强王者120星',
						create_time:1629108163,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'text',//images video  audio file share
						data:'厉害👍👍👍',
						create_time:1629367911,
						isremove:false
					},
					{
						avatar:'/static/images/index/logo5.jpg',
						user_id:1,
						nickname:'昵称',
						type:'video',//images video  audio file share
						data:'/static/video/demo.mp4',
						options:{
							poster:'/static/video/demo.jpg'
						},
						create_time:1629367911,
						isremove:false
					},
				],
				menus:[
					{
						name:"复制",
						event:"copy",
					},
					{
						name:"发送给朋友",
						event:"delChat",
					},
					{
						name:"收藏",
						event:"setTop",
					},
					{
						name:"提醒",
						event:"setTop",
					},
					{
						name:"翻译",
						event:"setTop",
					},
					{
						name:"删除",
						event:"setTop",
					},
					{
						name:"多选",
						event:"setTop",
					},
					{
						name:"撤回",
						event:"removeChatItem",
					},
				],
			}
		},
		mounted() {
			// // plus 在手机端是正常的,在浏览器不行
			// var statusBarHeight = plus.navigator.getStatusbarHeight()?plus.navigator.getStatusbarHeight():100;//动态获取 状态栏 的高度
			// console.log('statusBarHeight',statusBarHeight);
			// this.navBarHeight = statusBarHeight + uni.upx2px(200);//状态栏高度 + 自定义 导航 高度
			// console.log('this.navBarHeight',this.navBarHeight);
			
			// 监听键盘高度变化
			uni.onKeyboardHeightChange(res => {
				if(this.mode != 'action' && this.mode !== 'emoticon'){
					this.keyboardHeight = res.height;
				}
				if(this.keyboardHeight > 0){
					this.pageToBottom()
				}
			});
			//监听录音开始
			RECORD.onStart(()=>{
				this.RecordTime = 0
				// 定义一个计时器  来计算录音时长
				this.RECORDTIMER = setInterval(()=>{
					this.RecordTime++
				},1000)
			});
			// 监听录音结束
			RECORD.onStop((e)=>{
				// 需要清除定时器,并将时间真空
				if(this.RECORDTIMER){
					clearInterval(this.RECORDTIMER)
					this.RECORDTIMER = null
				}
				// unRecord 是用来判断  上滑是否取消发送   如果取消的话 unRecord:true 否者  false
				if(!this.unRecord){
					// 发送  
					this.send('audio',e.tempFilePath,{
						time:this.RecordTime
					})
				}
				
			})
		},
		onShow() {
			// 聊天定位到底部
			this.scrollToBottom();
		},
		onLoad(options) {
			this.title = '与'+options.title+'的聊天'
			let self = this;
			recorderManager.onStop(function (res) {
				console.log('recorder stop' + JSON.stringify(res));
				self.voicePath = res.tempFilePath;
			});
		},
		computed:{
			// 获取蒙版的位置
			maskBotto(){
				return this.keyboardHeight + uni.upx2px(105)
			},
			//动态获取菜单的高度
			getMenusHeight(){
				let H  = 100;
				return this.menus.length*H;
			},
			// 获取菜单的样式
			getMenusStyle(){
				return `height:${this.getMenusHeight}rpx`
			},
			//判断是否操作本人信息
			doSelf(){
				// 获取本人id(假设拿到)
				let id = 1;
				//索引是从 0 开始，肯定大于  -1
				let user_id = this.propIndex > -1 ? this.list[this.propIndex].user_id:0;
				return user_id === id;//如果是本人就相等  返回  true
			},
			//获取操作菜单
			menusList(){
				return this.menus.filter(v=>{
					if(v.name === '撤回' && !this.doSelf){
						return false
					}else{
						return true
					}
				})
			},
			// 聊天区域bottom
			chartBodyBottom(){
				return `bottom:${uni.upx2px(105) + this.keyboardHeight}px;top:${this.navBarHeight}px;`
			},
			// 获取操作表情列表
			emoticonOrActionList(){
				return (this.mode === 'emoticon' || this.mode === 'action')?this[this.mode+'List']:[]
			},
			// 所有信息的图片地址
			imageList(){
				let urlArr = []
				this.list.forEach(item=>{
					if(item.type === 'image' || item.type === 'emoticon'){
						urlArr.push(item.data)
					}
				})
				return urlArr;
			}
		},
		watch:{
			mode(newValue,oldValue){
				// if(newValue !== 'action'){
				// 	this.$refs.action.hiden()
				// }
				if(newValue !== 'text'){
					uni.hideKeyboard()
				}
				if(newValue === 'text'){
					this.$refs.action.hiden()
				}
			}
		},
		created() {
			// 初始化
			this.__init()
		},
		methods: {
			// 录音相关
			voiceTouchStart(e){
				// 初始化
				this.isRecording = true
				this.RecordingStartY = e.changedTouches[0].clientY
				this.unRecord = false
				// 开始录音
				RECORD.start({
					format:'mp3'
				})
			},
			//录音结束
			voiceTouchEnd(){
				this.isRecording = false
				// 停止录音
				RECORD.stop()
			},
			//录音被打断 取消发送
			ouchCancel(){
				this.isRecording = false
				this.unRecord = true
				// 停止录音
				RECORD.stop()
			},
			voiceTouchMove(e){
				let Y = Math.abs(e.changedTouches[0].clientY - this.RecordingStartY)
				this.unRecord = (Y >= 50)
			},
			// 开始录音
			startRecord(){
				console.log('开始录音');
				recorderManager.start();
			},
			// 输入模式的切换
			change(){
				this.mode = this.mode !== 'text'?'text':'audio'
			},
			//图片预览
			preview(url){
				// 预览图片
				uni.previewImage({
					current:url,
					urls:this.imageList,
					indicator:'default',
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('e.data',vm.url)
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			// 滚动
			scrollToBottom () {  //哪里需要用到就在哪里使用
				var vm = this;
				var num = Math.round(Math.random()*9999);
				vm.$nextTick(() => {
					vm.scrollTop = num*1000
				});
			},
			// 初始化 表情 数据
			__init(){
				var total = 20
				var page = Math.ceil(total/8)
				var arr = []
				for(var i = 0 ;i<page;i++){
					var start = i*8
					arr[i] = []
					for(var j = 0;j<8;j++){
						var no = start + j
						if((no+1)<total){
							arr[i].push({
								name:'表情'+(start+j),
								icon:'/static/images/emoticon/5497/'+(start+j)+'.gif',
								event:'sendEmoticon'
							})
							this.emoticonList = arr
						}
					}
				}
			},
			// 点击聊天界面,关闭底部菜单
			clickPage(){
				this.mode = ''
				this.$refs.action.hiden()
			},
			// 拓展菜单点击事件
			actionEvent(e){
				switch(e.event){
					case "uploadImage":
					this.chooseImage();
					break;
					case "sendEmoticon"://发送表情包
					this.send('emoticon',e.icon)
					break;
					case "uploadVideo"://发送短视频
					this.chooseVideo()
					break;
				};
			},
			//录制视频
			chooseVideo(){
				var self = this;
				uni.chooseVideo({
					maxDuration:10,				
					count: 1,
					success: function (res) {
						console.log('res.tempFilePath',res.tempFilePath);
						self.send('video',res.tempFilePath)
						// self.src = res.tempFilePath;  
						// 渲染页面
						// 发送到服务端（获取视频封面，返回url）
						//修改本地的发送状态
					}
				});
			},
			// 选择图片
			chooseImage(){
				var vm = this;
				// 从相册选择6张图
				uni.chooseImage({
				    count: 9,
				    sizeType: ['original', 'compressed'],
				    sourceType: ['album'],
				    success: function(res) {
						// 发送到服务器	
						// 渲染页面
						console.log('res.tempFilePaths',res.tempFilePaths)
						res.tempFilePaths.forEach((item)=>{
							vm.send('image',item)
						})
				    }
				    });
			},
			// 打开拓展菜单或者表情包
			openActionOrEmoticon(mode = 'action'){
				this.mode = mode
				this.$refs.action.show()
				uni.hideKeyboard()
				this.keyboardHeight = uni.upx2px(580)
			},
			// 发送
			send(type,data='',options = {}){
				var obj = {
					avatar:'/static/images/index/logo5.jpg',
					user_id:1,
					nickname:'昵称',
					type:type,//images video  audio file share emoticon
					data:data,
					options:options,
					create_time:(new Date()).getTime(),
					isremove:false
				}
				switch(type){
					case 'text':
					obj.data = this.text
						break;
				}
				this.list.push(obj)
				//信息内容发送后清空内容
				if(type === 'text'){
					this.text = '';
				}
				// 置于消息底部
				this.scrollToBottom();
			},
			//回到底部
			pageToBottom(){ 
				var chatItem = this.$refs.chatItem
				let lastIndex = chatItem.length > 0 ? chatItem.length - 1 : 0
				let last = chatItem[lastIndex]
			},
			// 返回上一页
			back(){
				uni.navigateBack({
				});
			},
			// 跳转聊天页面设置页
			toSet(){
				uni.navigateTo({
					url:'/pages/tabbar/chat/chat_set'
				})
			},
			// 长按消息气泡
			long(x,y,index){
				console.log('x,x,index',x,y,index);
				// 初始化 索引
				this.propIndex = index;
				// 显示菜单
				this.$refs.extend.show(x,y);
			},
			// 分发菜单事件
			clickEvent(event,name){
				switch(event){
					case "setTop":
					uni.showToast({
						icon:'none',
						title:this.list[this.propIndex].data
					})
					break;
					case "copy": //复制
					uni.setClipboardData({
					    data: this.list[this.propIndex].data
					});
					break;
					case "removeChatItem"://撤回
					if(this.propIndex > -1){
						this.list[this.propIndex].isremove = true
					}
					uni.showToast({
						icon:'success',
						title:'撤回成功'
					})
					break;
				};
				// 隐藏关闭菜单
				this.$refs.extend.hiden();
			},
		}
		
	}
</script>

<style>
	/*每个页面公共css */
	@import '@/common/free.css';
	@import '@/common/common.css';
	@import '@/common/comicon.css';
	@import '@/common/free-icons.css';
	scroll-view ::-webkit-scrollbar {
		width: 0;
		height: 0;
		background-color: transparent;
	}
	::-webkit-scrollbar {
	  display: none;
	}
	  .wrapper{
	       height:auto!important;
	   }

</style>
